package cat.joronya.supermanager.privateleague;

import java.text.NumberFormat;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cat.joronya.supermanager.DatabaseHelper;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.drawer.BaseActionBarActivity;
import cat.joronya.supermanager.team.MyTeamDetailActivity;
import cat.joronya.supermanager.team.MyTeamsListActivity;
import cat.joronya.supermanager.team.Team;

public class PrivateLeagueDetailFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>
{
	// pel Log
	private static final String TAG = "supermanager";
	
	// loader id
	private static final int LIST_LOADER = 0x01;
	
	// the adapter
	private PrivateLeagueAdapter adapter;
	
	/**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
    	DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam._ID, 			// 0
        DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam.NAME, 			// 1
        DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam.MANAGER, 		// 2
        DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam.CITY, 			// 3
        DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam.POINTS, 		// 4
        DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam.GENERAL,		// 5
        DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam.BROKER, 		// 6
        DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam.MODIFIED_DATE, // 7
        DatabaseHelper.MY_TEAM_TABLE_NAME+"."+Supermanager.MyTeam.ID_EQU 								// 8
    };
    
    // Gesture detection
    private GestureDetector gestureDetector;
    View.OnTouchListener gestureListener;
    
    private String league = "undefined";
    private long id = 0;
    private String jornada = "?";
    private String mCurOrder = Supermanager.PrivateLeagueTeam.DEFAULT_SORT_ORDER;
    private int selectedPosition = R.id.jornada;

    private Cursor daysCursor = null;
    
    private NumberFormat decform = null;
    private NumberFormat intform = null;
    
    // share purposes variables
    private Team myTeam;
    
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static PrivateLeagueDetailFragment newInstance(long id) 
    {
    	PrivateLeagueDetailFragment f = new PrivateLeagueDetailFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putLong("cat.joronya.supermanager.privateleague.id", id);
        f.setArguments(args);

        return f;
    }
    
    public long getShownIndex() 
    {
        return getArguments().getLong("cat.joronya.supermanager.privateleague.id", 0);
    }
    
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) 
	{
    	// If not container present, don't generate the view so this fragment
    	// is not visible. Doing so, may cause problems with FragmentManager on
    	// recreation of the activity when orientation changes occur and different
    	// layout is loaded with id's no present anymore on it.
    	if( container == null )
    	{
    		return null;
    	}
    	
    	View view = inflater.inflate(R.layout.private_league, null);
    	
        if( decform == null )
        {
        	decform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	decform.setMinimumFractionDigits(2);
        }
        if( intform == null )
        {
        	intform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	intform.setGroupingUsed(true);
        }
    	
        // inicialitzem el detector de gestures
        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };
        
        // registrem el gesture listener a les vistes del layout
        registerTouchListener(view);
        
        // guardem id, aixi el tenim quan reordenem el cursor
        id = getArguments().getLong("cat.joronya.supermanager.privateleague.id", 0);

        // recuperem el nom de la lliga i la jornada
        daysCursor = getDaysOfLeague(id);
        if( daysCursor.moveToLast() )
		{
			league = daysCursor.getString(1);
        	jornada = daysCursor.getString(2);
		}
        
        // avisem q el fragment te menu pq es cridi
        setHasOptionsMenu(true);
        
        // set title of activity
        ActionBarActivity ab = (ActionBarActivity)getActivity();
        ab.setTitle(getString(R.string.private_league_title, league, jornada));
        
    	return view;
	}
    
    @Override
	public void onActivityCreated(Bundle savedInstanceState) 
    {
		super.onActivityCreated(savedInstanceState);
		
		// if there's no visible view, we haven't created it, so nothing to do
		if( getView() == null )
			return;
				
        // creem adapter i el registrem
        adapter = new PrivateLeagueAdapter(getActivity().getApplicationContext(), null);
        setListAdapter(adapter);
	}
    
    @Override
    public void onResume() 
    {
    	// resetejem el loader per canviar recarregar si canvis al refresh team
        getLoaderManager().restartLoader(LIST_LOADER, null, this);
    	super.onResume();
    }
    
    public void getMyTeamInPrivateLeague()
	{
        // load manager name
        SharedPreferences settings = 
			PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
   		String manager = settings.getString(Supermanager.PREFS_USERNAME, null);
        
   		String orderClause;
   		switch(selectedPosition)
   		{
   			default:
   			case R.id.jornada:
   				orderClause = Supermanager.PrivateLeagueTeam.DEFAULT_SORT_ORDER;
   				break;
   			case R.id.general:
   				orderClause = Supermanager.PrivateLeagueTeam.GENERAL_SORT_ORDER;
   				break;
   			case R.id.broker:
   				orderClause = Supermanager.PrivateLeagueTeam.BROKER_SORT_ORDER;
   				break;
   		}
   		
		Cursor plCursor = getActivity().getContentResolver().query(Supermanager.PrivateLeagueTeam.CONTENT_URI, 
				PROJECTION, 
				DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID+" = ? AND "+
	       		DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam.DAY+" = ? ",
	       		new String[]{Long.toString(this.id),jornada},
	            orderClause);
		
		while( plCursor.moveToNext() )
		{
			String tm = plCursor.getString(2).trim();
			
			if( manager.equals(tm) )
			{
				myTeam = new Team();
				myTeam.setPositionOnLeague(plCursor.getPosition()+1);
				myTeam.setName(plCursor.getString(1));
				myTeam.setManager(tm);
				myTeam.setPoints(plCursor.getFloat(4));
				myTeam.setGeneral(plCursor.getFloat(5));
				myTeam.setBroker(plCursor.getInt(6));
			}
		}
		
		plCursor.close();
	}
    
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) 
	{
		String idequ = (String)v.getTag(R.id.team);
		if( idequ != null)
		{
			BaseActionBarActivity activity = (BaseActionBarActivity)getActivity();
			View detailsFrame = getActivity().findViewById(R.id.detail_fragment);
			boolean mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
			if( activity.isTablet() && mDualPane )
			{
				Intent intent = new Intent();
				intent.setClass(getActivity(), MyTeamsListActivity.class);
				intent.putExtra("cat.joronya.supermanager.myteams.idequ", Long.parseLong(idequ));
				startActivity(intent);
			}
			else
			{
				Intent intent = new Intent();
				intent.setClass(getActivity(), MyTeamDetailActivity.class);
				intent.putExtra("cat.joronya.supermanager.myteams.idequ", Long.parseLong(idequ));
				startActivity(intent);
			}
		}
		
		super.onListItemClick(l, v, position, id);
	}
	
    private void registerTouchListener(View view)
	{
        View listView = view.findViewById(android.R.id.list);
        listView.setOnTouchListener(gestureListener);
	}
    
    /**
	 * Retorna el cursor amb el llistat de jornades disponibles a l'historic
	 * de la lliga.
	 * @param id
	 * @return
	 */
	private Cursor getDaysOfLeague(long id)
	{
		 // recuperem el nom de la lliga i la jornada
        PrivateLeagueTeamProvider plTeamProvider = new PrivateLeagueTeamProvider();
        Cursor cursor = plTeamProvider.getPrivateLeagueDays(getActivity(), id);
        
        return cursor;
	}
	
	/**
	 * Select next day. And call show active classificacion.
	 */
	private void selectNextDay()
	{
		if( daysCursor.moveToNext() )
		{
			league = daysCursor.getString(1);
        	jornada = daysCursor.getString(2);
		
        	switch (selectedPosition) 
        	{
        		case R.id.jornada:
        			showTeamsJornada();
        			break;
        		case R.id.general:
        			showTeamsGeneral();
        			break;
        		case R.id.broker:
        			showTeamsBroker();
        			break;
        	}
        	
        	Toast.makeText(getActivity().getApplicationContext(), 
        			getResources().getString(R.string.private_league_activity_next_day, jornada), 
        			Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * Select previous day.
	 */
	private void selectPreviousDay()
	{
		if( daysCursor.moveToPrevious() )
		{
			league = daysCursor.getString(1);
        	jornada = daysCursor.getString(2);
		
        	switch (selectedPosition) 
        	{
        		case R.id.jornada:
        			showTeamsJornada();
        			break;
        		case R.id.general:
        			showTeamsGeneral();
        			break;
        		case R.id.broker:
        			showTeamsBroker();
        			break;
        	}
        	
        	Toast.makeText(getActivity().getApplicationContext(), 
        			getResources().getString(R.string.private_league_activity_previous_day, jornada), 
        			Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
    {
        inflater.inflate(R.menu.private_league, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
		// Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.jornada:
        		showTeamsJornada();
        		return true;
        	case R.id.general:
        		showTeamsGeneral();
        		return true;
        	case R.id.broker:
        		showTeamsBroker();
        		return true;
			case R.id.share:
				// prepare data to share
				getMyTeamInPrivateLeague();
				
				// team found?
				if( myTeam == null )
				{
					Toast.makeText(getActivity(), R.string.private_league_no_myteam, Toast.LENGTH_SHORT).show();
					return true;
				}
				
				int text;
				switch(selectedPosition)
		   		{
		   			default:
		   			case R.id.jornada:
		   				text = R.string.private_league_share_text_day;
		   				break;
		   			case R.id.general:
		   				text = R.string.private_league_share_text_general;
		   				break;
		   			case R.id.broker:
		   				text = R.string.private_league_share_text_broker;
		   				break;
		   		}
				
				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.putExtra(Intent.EXTRA_TEXT, 
					getString(text,	myTeam.getName(), myTeam.getPositionOnLeague(), league));
				sendIntent.setType("text/plain");
				startActivity(Intent.createChooser(sendIntent, getString(R.string.private_league_share_title)));
				return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
	
	class PrivateLeagueAdapter extends CursorAdapter 
	{
    	public PrivateLeagueAdapter(Context theContext, Cursor theCursor) 
		{
			super(theContext, theCursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) 
		{
			String name = cursor.getString(1);
			String manager = cursor.getString(2);
			String points = decform.format(cursor.getFloat(4));
			String general = decform.format(cursor.getFloat(5));
			String broker = intform.format(cursor.getInt(6));
			String id_equ = cursor.getInt(8)+"";
			
			TextView nameView = (TextView)view.findViewById(R.id.team);
			nameView.setText(name);
			TextView managerView = (TextView)view.findViewById(R.id.manager);
			managerView.setText(manager);
			TextView numView = (TextView)view.findViewById(R.id.points);
			switch(selectedPosition)
			{
				default:
				case R.id.jornada:
					numView.setText(points);
					break;
				case R.id.general:
					numView.setText(general);
					break;
				case R.id.broker:
					numView.setText(broker);
					break;
			}
			
			// es el meu equip?
			if( !"0".equals(id_equ) )
			{
				view.setBackgroundColor(getResources().getColor(R.color.orange));
				nameView.setTextColor(getResources().getColor(R.color.white));
				managerView.setTextColor(getResources().getColor(R.color.white));
				numView.setTextColor(getResources().getColor(R.color.white));
				
				// taggejem el id_equ per llançar el detall activity de my team
				view.setTag(R.id.team, id_equ);
			}
			else
			{
				view.setBackgroundColor(getResources().getColor(R.color.white));
				nameView.setTextColor(getResources().getColor(R.color.black));
				managerView.setTextColor(getResources().getColor(R.color.black));
				numView.setTextColor(getResources().getColor(R.color.black));
			}
			
			TextView positionView = (TextView)view.findViewById(R.id.position);
			positionView.setText((cursor.getPosition()+1)+"º");
			positionView.bringToFront();
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) 
		{
			// create the new view
			LayoutInflater inflater = LayoutInflater.from(context);
			RelativeLayout row = (RelativeLayout)inflater.inflate(R.layout.private_league_row, parent, false);
			return row;
		}
	}
    
	private void showTeamsJornada()
	{
		// marquem la posicio seleccionada
		selectedPosition = R.id.jornada;
		mCurOrder = Supermanager.PrivateLeagueTeam.DEFAULT_SORT_ORDER;
		
		// recarreguem el cursor, provocant el onCreateLoader
		getLoaderManager().restartLoader(LIST_LOADER, null,this);
	}
	
	private void showTeamsGeneral()
	{
		// marquem la posicio seleccionada
		selectedPosition = R.id.general;
		mCurOrder = Supermanager.PrivateLeagueTeam.GENERAL_SORT_ORDER;

		// recarreguem el cursor, provocant el onCreateLoader
		getLoaderManager().restartLoader(LIST_LOADER, null,this);
	}
	
	private void showTeamsBroker()
	{
		// marquem la posicio seleccionada
		selectedPosition = R.id.broker;
		mCurOrder = Supermanager.PrivateLeagueTeam.BROKER_SORT_ORDER;

		// recarreguem el cursor, provocant el onCreateLoader
		getLoaderManager().restartLoader(LIST_LOADER, null,this);
	}
	
	/**
	 * Gesture listener to tap left/right and move next/previous day results.
	 * @author pol
	 */
	class MyGestureDetector extends SimpleOnGestureListener 
	{
		private static final int SWIPE_MIN_DISTANCE = 120;
	    private static final int SWIPE_MAX_OFF_PATH = 250;
	    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	    
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) 
        {
            try 
            {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
                {
                    Log.d(TAG,"Left Swipe - nextDay");
                	selectNextDay();
                }
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
                {
                    Log.d(TAG,"Right Swipe - previousDay");
                    selectPreviousDay();
                }
                else
                {
                    Log.d(TAG,"else Swipe - no change");
                }
            } 
            catch (Exception e)
            {
                // nothing
            }
            return false;
        }
    }
	
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) 
	{
		CursorLoader cursorLoader = new CursorLoader(getActivity(),
				Supermanager.PrivateLeagueTeam.CONTENT_URI, 
				PROJECTION, 
				DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID+" = ? AND "+
				DatabaseHelper.PRIVATE_LEAGUE_TEAM_TABLE_NAME+"."+Supermanager.PrivateLeagueTeam.DAY+" = ? ",
	       		new String[]{Long.toString(this.id),jornada}, 
				mCurOrder);
	    return cursorLoader;
	}

	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) 
	{
		if( adapter!= null )
			adapter.swapCursor(cursor);
	}

	public void onLoaderReset(Loader<Cursor> loader) 
	{
		if( adapter!= null )
			adapter.swapCursor(null);
	}
}
